<?php

namespace app\home\service;

use think\Db;
use think\Controller;
use app\common\controller\WxPay;
use app\common\controller\AliPay;

class ApiService
{
    /**
     * 首页
     */
    static public function home()
    {
        $data = array();
        //轮播图
        $data['image'] = Db::name('home_image')->where('status', 1)->order('weigh desc')->select();
        foreach ($data['image'] as $key => $value) {
            $data['image'][$key]['image'] = 'http://'.$_SERVER['HTTP_HOST'].$value['image'];
            $data['image'][$key]['url'] = 'http://'.$_SERVER['HTTP_HOST'].'/home/api/image_article?id='.$value['id'];
        }
        //广告
        $data['adv'] = Db::name('home_adv')->where('status', 1)->order('weigh desc')->select();
        foreach ($data['adv'] as $key => $value) {
            $data['adv'][$key]['image'] = 'http://'.$_SERVER['HTTP_HOST'].$value['image'];
            $data['adv'][$key]['url'] = 'http://'.$_SERVER['HTTP_HOST'].'/home/api/adv_article?id='.$value['id'];
        }

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 注册站点列表
    */
    static public function register_station_list($address)
    {
        $data = array();
        if ($address) {
            $area = Db::name('area')->where('name', $address)->find();
            if ($area) {
                $data = Db::name('station')->where('area_id', $area['id'])->field('id, name, address')->select();
            }
        }
        
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
     * 会员注册
     */
    static public function member_register($sell_phone, $phone, $code, $password, $repetition, $member_name)
    {
        $data = array();
        if (!$station_id) {
            return array('code'=>201, 'msg'=>'请选择站点');
        }
        $station = Db::name('station')->where('id', $station_id)->find();
        if (!$station) {
            return array('code'=>201, 'msg'=>'站点选择有误');
        }
        $data['station_id'] = $station_id;
        if (!$phone) {
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        //判断是否注册
        $member = Db::name('member')->where('phone', $phone)->find();
        if ($member) {
            return array('code'=>201, 'msg'=>'账号已注册，请前往登录');
        }
        if (!$code) {
            return array('code'=>201, 'msg'=>'请输入验证码');
        }
        if (!$password) {
            return array('code'=>201, 'msg'=>'请输入密码');
        }
        if (!$repetition) {
            return array('code'=>201, 'msg'=>'请输入重复密码');
        }
        if($password !== $repetition){
            return array('code'=>201, 'msg'=>'两次密码输入不一致');
        }
        if (!$member_name) {
            return array('code'=>201, 'msg'=>'请输入真实姓名');
        }
        if (!$card_number) {
            return array('code'=>201, 'msg'=>'请输入身份证号码');
        }
        //检验身份证号
        if (strlen($card_number) !== 18) {
            return array('code'=>201, 'msg'=>'身份证号码有误');
        }
        if (!$file1) {
            return array('code'=>201, 'msg'=>'请上传身份证正面');
        }
        if (!$file2) {
            return array('code'=>201, 'msg'=>'请上传身份证反面');
        }

        //验证码是否有效
        $member_code = Db::name('member_code')->where('phone', $phone)->find();
        if(!$member_code){
            return array('code'=>201, 'msg'=>'请先发送验证码');
        }
        if($code !== $member_code['code']){
            return array('code'=>201, 'msg'=>'手机验证码有误');
        }
        if(time() > $member_code['expiretime']){
            return array('code'=>201, 'msg'=>'验证码过期，请重新发送');
        }
        //检测密码格式
        // $check_pass = self::valid_pass($password);
        // if(isset($check_pass['code']) || $check_pass['code'] == 201){
        //     return $check_pass;
        // }
        if (strlen($password)<6 || strlen($password)>20) {
            return array('code'=>201, 'msg'=>'密码长度为6-20位');
        }
        //业务邀请码
        if ($sell_phone) {
            $sell = Db::name('sell')->where('phone', $sell_phone)->find();
            if (!$sell) {
                return array('code'=>201, 'msg'=>'邀请人手机号有误');
            }
            $data['sell_id'] = $sell['id'];
            $data['sell_phone'] = $sell_phone;
            $data['sell_name'] = $sell['name'];
        }
        // 生成密码盐
        $salt = self::getRandChar();
        //上传图片
        $file1 = self::upload_image($file1);
        $data['card_front'] = $file1['data']['path'];
        //验证身份证正面照
        // $image_file = 'http://'.$_SERVER['HTTP_HOST'].$file1['data']['path'];
        // $result = self::check_card($image_file);
        // if (!$result) {
        //     return array('code'=>201, 'msg'=>'身份识别无法使用，请尽快续费');
        // }
        // $result = json_decode($result, true);

        // $info = array();
        // $info['name'] = $result['身份证识别实体信息']['身份证人像面实体信息']['姓名'];
        // $info['id_card'] = $result['身份证识别实体信息']['身份证人像面实体信息']['身份证号'];

        // if (!$info['name'] || !$info['id_card']) {
        //     return array('code'=>201, 'msg'=>'身份证正面照无法识别');
        // }
        // if ($info['id_card'] !== $card_number) {
        //     return array('code'=>201, 'msg'=>'身份证号码和图片不匹配');
        // }
        // if ($info['name'] !== $member_name) {
        //     return array('code'=>201, 'msg'=>'姓名和身份证姓名不匹配');
        // }

        $file2 = self::upload_image($file2);
        $data['card_reverse'] = $file2['data']['path'];
        // //验证身份证反面照
        // $image_file = 'http://'.$_SERVER['HTTP_HOST'].$file2['data']['path'];
        // $result = self::check_card($image_file);
        // if (!$result) {
        //     return array('code'=>201, 'msg'=>'身份识别无法使用，请尽快续费');
        // }
        // $result = json_decode($result, true);
        // $info = array();
        // $info['back'] = $result['身份证识别实体信息']['身份证国徽面实体信息']['签发机关'];
        // if (!$info['back']) {
        //     return array('code'=>201, 'msg'=>'身份证反面照无法识别');
        // }

        //注册
        $data['nick_name'] = $member_name;
        $data['member_name'] = $member_name;
        $data['card_number'] = $card_number;
        $data['phone'] = $phone;
        $data['sale'] = $salt;
        $data['password'] = md5(md5($password.$salt));
        $data['createtime'] = time();
        $data['member_img'] = '/uploads/member/default.png';
        //执行添加
        $result = Db::name('member')->insert($data);
        if(!$result){
            return array('code'=>201, 'msg'=>'网络异常');
        }
        //删除验证码
        Db::name('member_code')->where('phone', $phone)->delete();

        return array('code'=>200, 'msg'=>'注册成功');
    }

    /**
     * 身份证识别
     */
    static public function check_card($image_file)
    {
        //API产品路径
        $host = "https://personcard.market.alicloudapi.com";
        $path = "/ai_market/ai_ocr_universal/shen_fen_zheng/ch/v1";
        $method = "POST";
        //阿里云APPCODE
        $appcode = "e5a8403bf7ee46aaa5ee46ade582fd89";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        
        $querys = "";
        $bodys = "";
        $url = $host . $path;
        
        //参数配置
        //启用URL方式进行识别
        //内容数据类型是图像文件URL链接
        $IMAGE = $image_file;
        $IMAGE = urlencode($IMAGE);
        $IMAGE_TYPE = "1";
        
        $bodys = "IMAGE=".$IMAGE."&IMAGE_TYPE=".$IMAGE_TYPE;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $T = curl_exec($curl);

        return $T;
    }

    /**
     * 生成随机字符串
     */
    static public function getRandChar($length = 8, $is_str = true)
    {
        $str = null;
        $strPol = "0123456789";
        if ($is_str) {
            $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        }
        $max = strlen($strPol) - 1;
        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }

    /**
     * 验证密码格式
     */
    static function valid_pass($password)
    {
        $patt = '/^(?![^a-zA-Z]+$)(?!\D+$).{6,20}$/';
        if (!preg_match($patt, $password)) {
            return array('code'=>201, 'msg'=>'密码必须包含字母和数字，长度为6~20位');
        }
        return true;
    }

    /**
    * 用户密码登录
    */
    static public function member_login($phone, $password)
    {
        if(!$phone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        //检测用户是否存在
        $member = Db::name('member')->where('phone', $phone)->find();
        if(!$member){
            return array('code'=>201, 'msg'=>'账号未注册');
        } else {
            if ($member['status'] == 4) {
                return array('code'=>201, 'msg'=>'账号已被冻结');
            }
        }
        if(!$password){
            return array('code'=>201, 'msg'=>'请输入密码');
        }
        //验证密码
        $password = md5(md5($password.$member['sale']));
        if($password !== $member['password']){
            return array('code'=>201, 'msg'=>'密码输入有误');
        }
        //生成token
        $token = self::getRandChar(50);
        //数据处理
        $data = array();
        $data['token'] = $token;
        $data['createtime'] = time();
        $data['expiretime'] = strtotime("+7 day");
        $token_count = Db::name('member_token')->where('member_id', $member['id'])->count();
        $result = 0;
        if ($token_count) {
            $result = Db::name('member_token')->where('member_id', $member['id'])->update($data); 
        } else {
            $data['member_id']  = $member['id'];
            $result = Db::name('member_token')->insert($data); 
        }
        if($result < 1){
            return array('code'=>201, 'msg'=>'登录失败');
        }
        //返回数据
        $member_info = array();
        $member_info['phone'] = $member['phone'];
        $member_info['token'] = $token;
        $member_info['member_img'] = 'http://'.$_SERVER['HTTP_HOST'].$member['member_img'];
        $member_info['nick_name'] = $member['nick_name'];
        $member_info['member_name'] = $member['member_name'];
        $member_info['if_company'] = 0;
        $member_info['company_name'] = '';
        if ($member['company_id']) {
            $member_info['if_company'] = 1;
            $member_info['company_name'] = $member['company_name'];
        }
        $station = Db::name('station')->where('id', $member['station_id'])->find();
        $member_info['station_name'] = $station['name'];

        return array('code'=>200, 'msg'=>'登录成功', 'data'=>$member_info);
    }

    /**
    * 验证会员token是否有效
    */
    static public function check_member_token($token)
    {   
        $token = Db::name('member_token')->where('token', $token)->find();
        if(!$token){
            return array('code'=>202,'msg'=>'token无效');
        }
        if($token['expiretime'] < time()){
            return array('code'=>202,'msg'=>'token过期');
        }
        $member = Db::name('member')->where('id', $token['member_id'])->find();
        if (!$member) {
            return array('code'=>202,'msg'=>'token无效');
        }
        if ($member['status'] == 4) {
            return array('code'=>202,'msg'=>'token无效');
        }
        return $token;
    }

    /**
    * 用户退出
    */
    static public function member_logout($token)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测token是否有效
        $member_token = self::check_member_token($token);
        if(isset($member_token['code']) && $member_token['code'] == 202){
            return $member_token;
        }
        //执行删除用户token 
        $result = Db::name('member_token')->where('token', $token)->delete();
        
        if(!$result){
            return array('code'=>201, 'msg'=>'退出失败');
        }

        return array('code'=>200, 'msg'=>'退出成功');
    }

    /**
     * 上传单图
     */
    static public  function upload_image($file)
    {
        $filePath = 'member';
        $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS .$filePath;
        if (!file_exists($filePaths)) {
            mkdir($filePaths, 0777, true);
        }
        $info = $file->move($filePaths,self::create_file_name(20));
        if ($info) {
            $img_name = $info->getSaveName();
            $path = '/uploads/'.$filePath.'/'.$img_name;
            $data = array();
            $data['path'] = $path;
            return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
        } else {
            // 上传失败获取错误信息
            // return $file->getError();
            return array('code'=>201, 'msg'=>'失败');
        }
    }

    /**
     * 生成文件名称
     */
    static function create_file_name($length)
    {
        $str = '0123456789abcdefghijklmnopqrstuvwxyz';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++){
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    /**
    * 忘记密码
    */
    static public function forget_pass($phone, $code, $newpassword, $repassword)
    {
        if(!$phone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        if(!$code){
            return array('code'=>201, 'msg'=>'请输入验证码');
        }
        if(!$newpassword){
            return array('code'=>201, 'msg'=>'请输入新密码');
        }
        if(!$repassword){
            return array('code'=>201, 'msg'=>'请再次输入密码');
        }
        if($newpassword !== $repassword){
            return array('code'=>201, 'msg'=>'两次密码输入不一致');
        }
        
        //检测手机是否已经注册
        $member = Db::name('member')->where('phone', $phone)->find();
        if(!$member){
            return array('code'=>201, 'msg'=>'请先注册');
        }
        //检测验证码是否正确,并且检测验证码是否过期
        $member_code = Db::name('member_code')->where('phone', $phone)->find();
        if(!$member_code){
            return array('code'=>201, 'msg'=>'请先发送验证码');
        }
        //检测验证码是否正确
        if($code !== $member_code['code']){
            return array('code'=>201, 'msg'=>'手机验证码错误');
        }
        //检测验证码是否过期
        $time = time();
        if($time > $member_code['expiretime']){
            return array('code'=>201, 'msg'=>'验证码已过期,请重新发送');
        }
        //检测新密码是否符合密码规则
        // $check_pass = self::valid_pass($newpassword);
        // if(isset($check_pass['code']) && $check_pass['code'] == 201){
        //     return $check_pass;
        // }
        if (strlen($newpassword)<6 || strlen($newpassword)>20) {
            return array('code'=>201, 'msg'=>'密码长度为6-20位');
        }
        // 生成密码盐
        $sale = self::getRandChar();
        //封装修改条件及修改的数据
        $data = array();
        $data['password'] = md5(md5($newpassword.$sale));  
        $data['sale'] = $sale;
        //执行修改密码 
        Db::name('member')->where('phone', $phone)->update($data);
        //删除验证码
        Db::name('member_code')->where('phone', $phone)->delete();

        return array('code'=>200, 'msg'=>'修改成功');
    }

    /**
    * 修改绑定手机,验证旧手机
    */
    static public function change_old_phone($token, $old_phone, $code)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        if(!$old_phone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        if(!$code){
            return array('code'=>201, 'msg'=>'请输入手机验证码');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        $member_code = Db::name('member_code')->where('phone', $old_phone)->find();
        if(!$member_code){
            return array('code'=>201, 'msg'=>'请先发送验证码');
        }
        //检测验证码是否正确
        if($code !== $member_code['code']){
            return array('code'=>201, 'msg'=>'手机验证码错误');
        }
        //检测验证码是否过期
        $time = time();
        if($time > $member_code['expiretime']){
            return array('code'=>201, 'msg'=>'验证码已过期，请重新获取');
        }
        //删除验证码
        Db::name('member_code')->where('phone', $old_phone)->delete();
        return array('code'=>200, 'msg'=>'验证成功');
    }

    /**
    * 修改绑定手机
    */
    static public function change_new_phone($token, $newphone, $code)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        if(!$newphone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        if(!$code){
            return array('code'=>201, 'msg'=>'请输入手机验证码');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        //检测新手机号是否和原始手机号相同
        $where = array();
        $where['id'] = $member_id;
        $member_info = Db::name('member')->field('phone,member_name')->where($where)->find();
        if($newphone == $member_info['phone']){
            return array('code'=>201,'msg'=>'新手机号和原始手机号相同');
        }
        //查询验证码
        $where = array();
        $where['phone'] = $newphone;
        $mobilecode = Db::name('member_code')->where($where)->find();
        //判断验证码是否正确
        if($code !== $mobilecode['code']){
            return array('code' => 201, 'msg'=>'手机验证码错误');
        }
        //判断验证码是否过期
        $time = time();
        if($time > $mobilecode['expiretime']){
            return array('code' => 201, 'msg'=>'验证码已过期,请重新发送');
        }
        $data = array();
        $data['phone'] = $newphone;
        //判断用户是否修改了昵称
        if($member_info['phone'] == $member_info['member_name']){
            $data['member_name'] = $newphone;
        }
        //执行修改手机号
        $where = array();
        $where['id'] = $member_id;
        $result = Db::name('member')->where($where)->update($data);
        //删除验证码
        Db::name('member_code')->where('phone', $newphone)->delete();
        $data = array();
        $data['phone'] = $newphone;
        return array('code'=>200, 'msg'=>'修改成功', 'data'=>$data);
    }

    /**
    * 手机验证码登录
    */
    static public function phone_login($phone, $code)
    {
        if(!$phone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        if(!$code){
            return array('code'=>201, 'msg'=>'请输入验证码');
        }
        //检测用户是否存在
        $member = Db::name('member')->where('phone', $phone)->find();
        if(!$member){
            return array('code'=>201, 'msg'=>'请先注册');
        } else {
            if ($member['status'] == 4) {
                return array('code'=>201, 'msg'=>'账号已被冻结');
            }
        }
        $member_code = Db::name('member_code')->where('phone', $phone)->find();
        if(!$member_code){
            return array('code'=>201, 'msg'=>'请先发送验证码');
        }
        //检测验证码是否正确
        if($code !== $member_code['code']){
            return array('code'=>201, 'msg'=>'手机验证码错误');
        }
        //检测验证码是否过期
        $time = time();
        if($time > $member_code['expiretime']){
            return array('code'=>201, 'msg'=>'验证码已过期，请重新获取');
        }

        //生成token签名
        $token = '';
        $token = self::getRandChar(50);
        //封装添加用户token数据
        $data = array();
        $data['token'] = $token;
        $data['createtime'] = time();
        $data['expiretime'] = strtotime("+7 day");
        $where = array();
        $where['member_id'] = $member['id'];
        $member_token_count = Db::name('member_token')->where('member_id', $member['id'])->count();
        if ($member_token_count) {
            //执行修改
            $member_token_res = Db::name('member_token')->where('member_id', $member['id'])->update($data); 
        } else {
            $data['member_id']  = $member['id'];
            //执行添加
            $member_token_res = Db::name('member_token')->insert($data); 
        }
        if (!$member_token_res) {
            return array('code'=>201, 'msg'=>'token生成失败');
        }
        //删除验证码
        Db::name('member_code')->where('phone', $phone)->delete();
        //返回数据
        $member_info = array();
        $member_info['phone'] = $member['phone'];
        $member_info['token'] = $token;
        $member_info['member_img'] = 'http://'.$_SERVER['HTTP_HOST'].$member['member_img'];
        $member_info['nick_name'] = $member['nick_name'];
        $member_info['member_name'] = $member['member_name'];
        $member_info['if_company'] = 0;
        $member_info['company_name'] = '';
        if ($member['company_id']) {
            $member_info['if_company'] = 1;
            $member_info['company_name'] = $member['company_name'];
        }
        $station = Db::name('station')->where('id', $member['station_id'])->find();
        $member_info['station_name'] = $station['name'];

        return array('code'=>200, 'msg'=>'成功', 'data'=>$member_info);
    }

    /**
    * 会员修改头像
    */
    static public function member_upload_img($token, $file)
    {
        if (!$token) {
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        if (!$file) {
            return array('code'=>201, 'msg'=>'请上传头像');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        $file1 = self::upload_image($file);
        //执行修改
        $data = array();
        $data['member_img'] = $file1['data']['path'];
        $result = Db::name('member')->where('id', $member_id)->update($data);
        $data['member_img'] = 'http://'.$_SERVER['HTTP_HOST'].$data['member_img'];
        
        return array('code'=>200, 'msg'=>'修改成功', 'data'=>$data);
    }

    /** 
    * 修改昵称
    */
    static public function change_member_name($token, $nick_name)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        if(!$nick_name){
            return array('code'=>201, 'msg'=>'修改昵称不能为空');
        }
        //检测用户token是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }

        $member_id = $check_member_token['member_id'];
        $where = array();
        $where['id'] = $member_id;
        $data['nick_name'] = $nick_name;
        Db::name('member')->where($where)->update($data);

        return array('code'=>200, 'msg'=>'修改成功', 'data'=>$data);
    }

    /**
     * 发送手机验证码
     */
    static public function send_code($phone, $type)
    {
        // type 1=注册，2=登录，3=忘记密码，4=修改手机号(旧手机号)，5=修改手机号(新手机号)
        if(!$phone){
            return array('code'=>201, 'msg'=>'请输入手机号');
        }
        $phone = base64_decode($phone);
        $phone = str_replace('zuche', '', $phone);
        $phone = base64_decode($phone);
        $res = self::check_phone($phone);
        if (isset($res['code'])) {
            return $res;
        }
        //手机号是否已经注册
        $count = Db::name('member')->where('phone', $phone)->count();
        if ($type == 1) {
            if ($count > 0) {
                return array('code'=>201, 'msg'=>'手机号已注册，请前往登录');
            }
        } elseif ($type == 2 || $type == 3) {
            if ($count < 1) {
                return array('code'=>201, 'msg'=>'请先注册');
            }
        } elseif ($type == 5) {
            if ($count > 0) {
                return array('code'=>201, 'msg'=>'请使用未注册过的手机号');
            }
        }
        //发送短信
        $smsapi = "http://www.smsbao.com/"; //短信网关
        $user = "zhaojincong"; //短信平台帐号
        $pass = md5("dc123."); //短信平台密码
        $random = self::getRandChar(6, false);
        $content = "【尚博德睿】您的验证码是：{$random}，5分钟内有效，如非本人操作，请忽略本短信！";//要发送的短信内容
        $phone = $phone;
        $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
        $result = file_get_contents($sendurl);
        if ($result !== '0') {
            return array('code'=>201, 'msg'=>'网络异常');
        }
        //处理数据
        $data = array();
        $data['code'] = $random;
        $data['createtime'] = time();
        $data['expiretime'] = time() + 5*60;
        $count = Db::name('member_code')->where('phone', $phone)->count();
        if ($count < 1) {
            $data['phone'] = $phone;
            Db::name('member_code')->insert($data);
        } else {
            Db::name('member_code')->where('phone', $phone)->update($data);
        }

        return array('code'=>200, 'msg'=>'发送成功');
    }

    /**
     * 验证手机号格式
     */
    static public function check_phone($phone)
    {
        if (!preg_match("/^(13|14|15|17|18|19)(\d{9})$/i", $phone)) {
            return array('code'=>201, 'msg'=>'手机号格式有误');
        }
        return true;
    }

    /**
    * 修改密码
    */
    static public function change_pass($token, $old_pass, $new_pass, $re_pass)
    {
        if (!$token) {
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测token是否有效
        $member_token = self::check_member_token($token);
        if(isset($member_token['code']) && $member_token['code'] == 202){
            return $member_token;
        }
        if (!$old_pass) {
            return array('code'=>201, 'msg'=>'请输入旧密码');
        }
        if (!$new_pass) {
            return array('code'=>201, 'msg'=>'请输入新密码');
        }
        if (!$re_pass) {
            return array('code'=>201, 'msg'=>'请再次输入密码');
        }
        //查询修改密码的用户
        $member_info = Db::name('member')->where('id', $member_token['member_id'])->find();
        //检测原始密码是否正确
        $password = md5(md5($old_pass.$member_info['sale']));
        if($password !== $member_info['password']){
            return array('code'=>201, 'msg'=>'旧密码错误');
        }
        if($old_pass == $new_pass){
            return array('code'=>201, 'msg'=>'旧密码和新密码不能相同');
        }
        if($new_pass !== $re_pass){
            return array('code'=>201, 'msg'=>'新密码和重复密码不相同');
        }

        //检测新密码是否符合密码规则
        // $check_pass = self::valid_pass($new_pass);
        // if(isset($check_pass['code']) && $check_pass['code'] == 201){
        //     return $check_pass;
        // }
        if (strlen($new_pass)<6 || strlen($new_pass)>20) {
            return array('code'=>201, 'msg'=>'密码长度为6-20位');
        }
        // 生成密码盐
        $sale = self::getRandChar();

        //封装修改条件及修改的数据
        $where = array();
        $where['id'] = $member_info['id'];
        $data = array();
        $data['password'] = md5(md5($new_pass.$sale));  
        $data['sale'] = $sale;  
        //执行修改密码 
        $result = Db::name('member')->where($where)->update($data);
        if(!$result){
            return array('code'=>201, 'msg'=>'网络异常');
        }
        
        return array('code'=>200, 'msg'=>'密码修改成功');
    }

    /**
    * 租车页面
    */
    static public function create_order($token)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        $data = array();
        $data['classify'] = Db::name('classify')->order('weigh desc')->select();
        if ($data['classify']) {
            foreach ($data['classify'] as $key => $value) {
                $rent_list = Db::name('rent')->where('classify_id', $value['id'])->order('weigh desc')->select();
                foreach ($rent_list as $k => $v) {
                    $rent_list[$k]['image'] = 'http://'.$_SERVER['HTTP_HOST'].$v['image'];
                }
                $data['classify'][$key]['rent_list'] = $rent_list;
            }
        }

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 租车页面计算价格
    */
    static public function compute_price($token, $rent_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        $member = Db::name('member')->where('id', $member_id)->find();
        $data = array();
        //计算租金，押金，需要支付的费用
        $data['rent_price'] = 0;
        $data['cash_price'] = 0;
        $data['total_price'] = 0;
        if ($rent_id) {
            $rent = Db::name('rent')->where('id', $rent_id)->find();
            if ($rent) {
                $data['rent_price'] = $rent['rent_price'];
                $data['cash_price'] = $rent['cash_price'];
                if ($member['company_id']) {
                    if ($rent['if_pay'] == 0) {
                        $data['total_price'] = 0;
                    } else {
                        $data['total_price'] = $rent['rent_price'];
                    }
                } else {
                    $data['total_price'] = $rent['rent_price'];
                }
            } else {
                return array('code'=>201, 'msg'=>'请求异常');
            }
        }

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 生成订单号及支付号
    */
    static public function create_number($l_num = 100, $r_num = 999, $type = 1, $member_id)
    {       
        if($type == 1){
            return $order_sn = substr(time(),3).$member_id.mt_rand($l_num,$r_num);
        }else if($type == 2){
            return $payment_num = $member_id.time().mt_rand($l_num,$r_num);
        }
    }

    /**
    * 提交订单
    */
    static public function commit_order($token, $rent_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        //判断用户状态
        $member = Db::name('member')->where('id', $member_id)->find();
        if ($member['status'] == 1) {
            return array('code'=>201, 'msg'=>'您的信息正在审核中，无法下单');
        }
        if ($member['status'] == 2) {
            return array('code'=>201, 'msg'=>'您的信息审核未通过，无法下单');
        }
        //判断是否有未完成的订单
        $where = array();
        $where['member_id'] = $member_id;
        $where['order_status'] = array('in', [1,2,3,4,5,6]);
        $order = Db::name('order')->where($where)->find();
        if ($order) {
            return array('code'=>201, 'msg'=>'您还有未完成的订单，无法下单');
        }
        if (!$rent_id) {
            return array('code'=>201, 'msg'=>'请选择套餐');
        }
        $rent = Db::name('rent')->where('id', $rent_id)->find();
        if (!$rent) {
            return array('code'=>201, 'msg'=>'套餐选择有误');
        }

        //生成订单
        $data = array();
        $order_sn = self::create_number(100, 999, 2, $member_id);
        $data['order_sn'] = $order_sn;
        $data['phone'] = $member['phone'];
        $data['member_id'] = $member_id;
        $data['member_name'] = $member['member_name'];
        $data['rent_id'] = $rent_id;
        $data['rent_name'] = $rent['name'];
        $data['type'] = $rent['type'];
        $data['rent_price'] = $rent['rent_price'];
        $data['cash_price'] = $rent['cash_price'];
        $data['total_price'] = $rent['rent_price'] + $rent['cash_price'];
        $data['order_status'] = 1;
        if ($member['company_id']) {
            $data['company_id'] = $member['company_id'];
            $data['company_name'] = $member['company_name'];
            //判断是否需要支付
            if ($rent['if_pay'] == 0) {
                $data['order_status'] = 2;
            }
        }
        $data['station_id'] = $member['station_id'];
        $data['createtime'] = time();
        if ($member['sell_id']) {
            $sell = Db::name('sell')->where('id', $member['sell_id'])->find();
            $data['sell_id'] = $sell['id'];
            $data['sell_phone'] = $sell['phone'];
            $data['sell_name'] = $sell['name'];
        }

        //添加订单到数据库
        $result = Db::name('order')->insertGetId($data);
        if ($result) {
            //添加订单消息
            $arr = array();
            $arr['member_id'] = $member_id;
            $arr['title'] = '新订单';
            $arr['content'] = '您有一个新的订单，请及时关注订单消息。';
            $arr['createtime'] = time();
            Db::name('message_order')->insert($arr);
            
            $info = array();
            $info['order_sn'] = $order_sn;
            $info['if_pay'] = $data['order_status'];
            return array('code'=>200, 'msg'=>'订单生成成功', 'data'=>$info);
        } else {
            return array('code'=>201, 'msg'=>'网络异常');
        }
    }

    /**
    * 支付
    */
    static public function pay_order($token, $order_sn, $payment_code)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        if(!$order_sn){
            return array('code'=>201, 'msg'=>'订单号不能为空');
        }
        if(!$payment_code){
            return array('code'=>201, 'msg'=>'请选择支付方式');
        }
        $order_info = Db::name('order')->where(array('order_sn'=>$order_sn, 'order_status'=>1))->find();
        if(!$order_info){
            return array('code'=>201, 'msg'=>'订单异常');
        }
        $out_trade_no = $order_sn;
        $total_fee = $order_info['rent_price'];

        switch($payment_code)
        {
            case 1;
                $body = '尚博德睿'; //描述
                // $total_fee = $total_fee * 100;//支付金额(乘以100)
                $total_fee = 1;
                $notify_url = 'http://zuche.zhaojincong.top/home/api/wxpayNotify/';//回调地址
                $wxpay = new WxPay();
                $result = $wxpay->unified_order($body,$total_fee,$out_trade_no,$notify_url);
                return array('code'=>200, 'msg'=>'成功', 'data'=>$result);
                break;
            case 2;
                $ali = new AliPay();
                $body = '尚博德睿'; //描述
                $total_fee = 0.01;
                $notify_url = 'http://zuche.zhaojincong.top/home/api/aliPayBack/';//回调地址
                $result = $ali->aliPay($body,$total_fee,$out_trade_no,$notify_url);
                $data = array();
                $data['alipay'] = $result;
                return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
                break;
        }
    }

    /**
     * 微信回调
     */
    static public function wxpayNotify() {  

        ini_set('date.timezone', 'Asia/Shanghai');
        error_reporting(E_ERROR);
        $xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $objectxml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = array();
        $json = json_encode($objectxml);
        $data = json_decode($json,true);
        $member_order = Db::name('order')->where('order_sn', $data['out_trade_no'])->find();
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS' && $member_order['order_status'] == 1) {
            // 启动事务
            Db::startTrans();
            try{
                //修改订单状态
                $arr = array();
                $arr['order_status'] = 2;
                $arr['payment_code'] = 1;
                $arr['if_rent'] = 1;
                Db::name('order')->where('order_sn', $data['out_trade_no'])->update($arr);
                Db::commit();

                //返回数据
                $arr = array();
                $arr['order_sn'] = $data['out_trade_no'];
                return array('code'=>200, 'msg'=>'支付成功', 'data'=>$arr);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return array('code'=>201, 'msg'=>'支付失败');
            }
        }
    }

    /**
    * 支付宝回调
    */
    static public function aliPayBack()
    {
        import('Alipay.AopClient',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr/u+YMMl4rKaDMuKa0QSg37Wk4ZcDoXz9I+v4MSYELwVLfu3CLmNWRrzH+6k2ivRaB0ZQl9e97Fud9MJTPJewYNC+LNTRhobW6DEm+H2Ffe4V1J9eSOs2giz0EAhKVggrqGsIUit1gmiuFPzi/9h6zsamOqFQ6zcNHwB19PORJDEIYAJ1ucleQwMUklfD4EttXXYQUqm94CTqbQJZwy9cr8J3buQ60N0S0cyPoHkw+jAJL8ZPkpDcYGOcDfiq/Op0bfIqYVQkJF1jFniDNNqfu68uq3BhxAeJRq0KuUgyNdTC8JAvV6rOsQ2cjlmspANfqQCf2bjCYnHEBUZFDbHGwIDAQAB';
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        $member_order = Db::name('order')->where('order_sn', $_POST['out_trade_no'])->find();
        if($flag && !isset($_POST['refund_fee']) && $member_order['order_status'] == 1){
            // 启动事务
            Db::startTrans();
            try{
                //修改订单状态
                $arr = array();
                $arr['order_status'] = 2;
                $arr['payment_code'] = 2;
                $arr['if_rent'] = 1;
                Db::name('order')->where('order_sn', $_POST['out_trade_no'])->update($arr);
                
                Db::commit();
                //返回数据
                $arr = array();
                $arr['order_sn'] = $_POST['out_trade_no'];
                return array('code'=>200, 'msg'=>'支付成功', 'data'=>$arr);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return array('code'=>201, 'msg'=>'支付失败');
            }
        }
    }

    /**
     * 判断业务是否正确
     */
    static public function judge_rent($token, $type1, $type2)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        //获取该账号下的订单需要哪种方式
        $where = array();
        $where['member_id'] = $member_id;
        $where['order_status'] = array('between', [2, 3]);
        $order = Db::name('order')->where($where)->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'您没有该业务');
        }
        if (!$type1) {
            return array('code'=>201, 'msg'=>'请选择租赁或者归还');
        }
        if (!$type2) {
            return array('code'=>201, 'msg'=>'请选择车或者电池');
        }
        //判断业务
        if ($order['order_status'] == 2 && $type1 == 2) {
            return array('code'=>201, 'msg'=>'业务有误');
        }
        if ($order['order_status'] == 3 && $type1 == 1) {
            return array('code'=>201, 'msg'=>'业务有误');
        }
        if ($order['type'] == 2 && $type2 == 1) {
            return array('code'=>201, 'msg'=>'请选择电池');
        }
        if ($order['type'] !== 2 && $type2 == 2) {
            return array('code'=>201, 'msg'=>'请选择车');
        }

        return array('code'=>200, 'msg'=>'成功');
    }

    /**
     * 租车还车上传图片
     */
    static public function rent_image($token, $order_id, $type, $card_number, $name1, $name2, $name3, $name4, $name5, $name6, $name7, $name8, $name9, $name10, $name11, $name12, $remark, $file)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        //判断订单
        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择订单');
        }
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        if (!$type) {
            return array('code'=>201, 'msg'=>'请选择要办理的业务');
        }
        //判断业务,租车还是退车
        if ($order['order_status'] == 3) {
            if ($type != 1) {
                return array('code'=>201, 'msg'=>'业务有误');
            }
        } elseif ($order['order_status'] == 6) {
            if ($type != 2) {
                return array('code'=>201, 'msg'=>'业务有误');
            }
        } else {
            return array('code'=>201, 'msg'=>'业务有误');
        }
        //上传信息
        $data = array();
        $data['type'] = $type;
        $data['order_id'] = $order['id'];
        $data['order_sn'] = $order['order_sn'];
        $data['member_id'] = $order['member_id'];
        if ($order['type'] == 2) {
            $data['card_number'] = $card_number;
            $data['name1'] = $name1;
            $data['name2'] = $name2;
            $data['name3'] = $name3;
            $data['name4'] = $name4;
            $data['name5'] = $name5;
            $data['name6'] = $name6;
            $data['name7'] = $name7;
            $data['name8'] = $name8;
            $data['name9'] = $name9;
            $data['name10'] = $name10;
            $data['name11'] = $name11;
            $data['name12'] = $name12;
        }
        $data['remark'] = $remark;
        //上传图片
        $result = array();
        foreach ($file as $key => $value){
            $file_name = self::upload_image($value);
            $result[$key] = $file_name['data']['path'];
        }
        $data['image'] = implode(',', $result);
        //启动事务
        Db::startTrans();
        try{
            //车辆是否在使用中
            if ($type == 1 && $order['type'] == 2) {
                $goods = Db::name('goods')->where('number', $card_number)->find();
                if (!$goods) {
                    return array('code'=>201, 'msg'=>'车牌号有误');
                }
                if ($goods['status'] == 2) {
                    return array('code'=>201, 'msg'=>'该车辆已被占用');
                }
            }
            $insert_id = Db::name('rent_info')->insertGetId($data);
            if (!$insert_id) {
                return array('code'=>201, 'msg'=>'上传失败');
            }

            //如果是租
            if ($order['order_status'] == 3) {
                //有车
                if ($order['type'] == 2) {
                    //修改车辆信息
                    $goods_info = array();
                    $goods_info['status'] = 2;
                    Db::name('goods')->where('number', $card_number)->update($goods_info);
                    //修改订单信息
                    $arr = array();
                    $arr['card_number'] = $card_number;
                    $goods = Db::name('goods')->where('number', $card_number)->find();
                    $arr['shareholder_id'] = $goods['shareholder_id'];
                    $shareholder = Db::name('shareholder')->where('id', $goods['shareholder_id'])->find();
                    $arr['shareholder_name'] = $shareholder['name'];
                    $arr['order_status'] = 4;
                    $arr['start_time'] = time();
                    $arr['cash_time'] = strtotime('+1 month');
                    $rent = Db::name('rent')->where('id', $order['rent_id'])->find();
                    $total_month = $rent['total_month'] + $rent['free_month'];
                    $month = '+'.$total_month.' month';
                    $arr['expire_time'] = strtotime($month);
                    $up_id = Db::name('order')->where('id', $order['id'])->update($arr);
                    if (!$up_id) {
                        return array('code'=>201, 'msg'=>'上传失败');
                    }
                } else {
                    //只有电
                    $arr = array();
                    //修改订单信息
                    $arr = array();
                    $arr['order_status'] = 4;
                    $arr['start_time'] = time();
                    $arr['cash_time'] = strtotime('+1 month');
                    $rent = Db::name('rent')->where('id', $order['rent_id'])->find();
                    $total_month = $rent['total_month'] + $rent['free_month'];
                    $month = '+'.$total_month.' month';
                    $arr['expire_time'] = strtotime($month);
                    $up_id = Db::name('order')->where('id', $order['id'])->update($arr);
                    if (!$up_id) {
                        return array('code'=>201, 'msg'=>'上传失败');
                    }
                }
            }

            //如果是退
            if ($order['order_status'] == 6) {
                $arr = array();
                $arr['return_time'] = time();
                $up_id = Db::name('order')->where('id', $order['id'])->update($arr);
                if (!$up_id) {
                    return array('code'=>201, 'msg'=>'上传失败');
                }
            }
            
            Db::commit();
            return array('code'=>200, 'msg'=>'上传成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return array('code'=>201, 'msg'=>'上传失败');
        }
    }

    /**
    * 小哥发布修改信息
    */
    static public function create_article($token, $content, $name, $phone, $file, $type, $article_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$content) {
            return array('code'=>201, 'msg'=>'请输入发布内容');
        }
        if (!$name) {
            return array('code'=>201, 'msg'=>'请输入发布人');
        }
        if (!$phone) {
            return array('code'=>201, 'msg'=>'请输入联系方式');
        }
        if (!$type) {
            return array('code'=>201, 'msg'=>'请求异常');
        }
        if ($type == 2) {
            if (!$article_id) {
                return array('code'=>201, 'msg'=>'请选择要修改的信息');
            }
            $article = Db::name('article')->where(array('id'=>$article_id, 'member_id'=>$member_id, 'status'=>1))->find();
            if (!$article) {
                return array('code'=>201, 'msg'=>'请求异常');
            }
        }
        $image = '';
        if ($file) {
            $result = array();
            foreach ($file as $key => $value){
                $file1 = self::upload_image($value);
                $result[$key] = $file1['data']['path'];
            }
            $image = implode(',', $result);
        }

        $data = array();
        $data['content'] = $content;
        $data['name'] = $name;
        $data['phone'] = $phone;
        $data['image'] = $image;
        if ($type == 1) {
            $data['member_id'] = $member_id;
            $data['createtime'] = time();
            $article = Db::name('article')->insertGetId($data);
            if ($article) {
                return array('code'=>200, 'msg'=>'发布成功');
            } else {
                return array('code'=>201, 'msg'=>'发布失败');
            }
        } else {
            Db::name('article')->where('id', $article_id)->update($data);
            return array('code'=>200, 'msg'=>'修改成功');
        }
        
    }

    /**
    * 小哥发布信息列表
    */
    static public function article_list($token, $page)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$page) {
            $page = 1;
        }
        $num = 6;
        $start_num = ($page-1)*$num;
        $data = array();
        $count = Db::name('article')->where('status', 1)->count();
        $total_page = ceil($count/$num);
        $article = Db::name('article')->where('status', 1)->order('id desc')->limit($start_num, $num)->select();
        foreach ($article as $key => $value) {
            if ($value['member_id'] == $member_id) {
                $article[$key]['is_self'] = 1;
            } else {
                $article[$key]['is_self'] = 0;
            }
            $article[$key]['createtime'] = date('Y-m-d', $value['createtime']);
            $image = array();
            if ($value['image']) {
                $image = explode(',', $value['image']);
                foreach ($image as $k => $v) {
                    $image[$k] = 'http://'.$_SERVER['HTTP_HOST'].$v;
                }
            }
            $article[$key]['image'] = $image;
        }
        $data['article'] = $article;
        $data['total_page'] = $total_page;
        
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 删除信息
    */
    static public function del_article($token, $article_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$article_id) {
            return array('code'=>201, 'msg'=>'请选择要删除的信息');
        }
        $article = Db::name('article')->where(array('id'=>$article_id, 'status'=>1, 'member_id'=>$member_id))->find();
        if (!$article) {
            return array('code'=>201, 'msg'=>'请求有误');
        }
        //删除
        $data = array();
        $data['status'] = 2;
        Db::name('article')->where('id', $article_id)->update($data);

        return array('code'=>200, 'msg'=>'删除成功');
    }

    /**
    * 订单列表
    */
    static public function order_list($token, $page)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        //判断是否有过期未支付订单
        $order = Db::name('order')->where(array('member_id'=>$member_id, 'order_status'=>1))->find();
        if ($order) {
            if ($order['createtime']+900 < time()) {
                $arr = array();
                $arr['order_status'] = 0;
                Db::name('order')->where('id', $order['id'])->update($arr);
            }
        }
        if (!$page) {
            $page = 1;
        }
        $data = array();
        $num = 6;
        $start_num = ($page-1)*$num;
        $count = Db::name('order')->where('member_id', $member_id)->count();
        $data['total_page'] = ceil($count/$num);
        $order = Db::name('order')->where('member_id', $member_id)->field('id, order_sn, rent_name, rent_price, cash_price, total_price, order_status, createtime, type, if_cash')->limit($start_num, $num)->order('id desc')->select();
        foreach ($order as $key => $value) {
            $order[$key]['createtime'] = date('Y-m-d H:i', $value['createtime']);
            $order[$key]['type'] = $value['type'];
            $order[$key]['if_cash'] = 1;
            $order[$key]['if_upload'] = 1;
            //订单状态:0=已取消,1=待支付,2=提车审核,3=审核通过,4=使用中,5=归还申请,6=退车中,7=已完成
            if ($value['order_status'] == 0) {
                $order[$key]['status_name'] = '已取消';
            }
            if ($value['order_status'] == 1) {
                $order[$key]['status_name'] = '待支付';
            }
            if ($value['order_status'] == 2) {
                $order[$key]['status_name'] = '提车审核中';
            }
            if ($value['order_status'] == 3) {
                $order[$key]['status_name'] = '审核通过';
            }
            if ($value['order_status'] == 4) {
                $order[$key]['status_name'] = '使用中';
                if ($value['if_cash'] == 0) {
                    $order[$key]['if_cash'] = 0;
                }
            }
            if ($value['order_status'] == 5) {
                $order[$key]['status_name'] = '退车申请';
            }
            if ($value['order_status'] == 6) {
                $order[$key]['status_name'] = '退车中';
                $rent_info = Db::name('rent_info')->where(array('type'=>2, 'order_id'=>$value['id']))->find();
                if (!$rent_info) {
                    $order[$key]['if_upload'] = 0;
                }
            }
            if ($value['order_status'] == 7) {
                $order[$key]['status_name'] = '已完成';
            }
        }
        $data['order'] = $order;
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 删除订单
    */
    static public function del_order($token, $order_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择要删除的订单');
        }
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id, 'is_show'=>0))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        if ($order['order_status'] > 0 && $order['order_status'] < 5) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        $data = array();
        $data['is_show'] = 1;
        $result = Db::name('order')->where('id', $order_id)->update($data);
        if (!$result) {
            return array('code'=>201, 'msg'=>'删除失败');
        }
        return array('code'=>200, 'msg'=>'删除成功');
    }

    /**
    * 取消订单
    */
    static public function cancel_order($token, $order_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择要取消的订单');
        }
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id, 'order_status'=>1))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        $data = array();
        $data['order_status'] = 0;
        $result = Db::name('order')->where('id', $order_id)->update($data);
        if (!$result) {
            return array('code'=>201, 'msg'=>'操作失败');
        }
        return array('code'=>200, 'msg'=>'订单已取消');
    }

    /**
    * 订单详情
    */
    static public function order_detail($token, $order_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择要查看的订单');
        }
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        //订单状态:0=已取消,1=待支付,2=提车审核,3=审核通过,4=使用中,5=归还申请,6=退车中,7=已完成
        if ($order['order_status'] == 0) {
            $order['order_status'] = '已取消';
        }
        if ($order['order_status'] == 1) {
            $order['order_status'] = '待支付';
        }
        if ($order['order_status'] == 2) {
            $order['order_status'] = '提车审核中';
        }
        if ($order['order_status'] == 3) {
            $order['order_status'] = '审核通过';
        }
        if ($order['order_status'] == 4) {
            $order['order_status'] = '使用中';
        }
        if ($order['order_status'] == 5) {
            $order['order_status'] = '退车申请';
        }
        if ($order['order_status'] == 6) {
            $order['order_status'] = '退车中';
        }
        if ($order['order_status'] == 7) {
            $order['order_status'] = '已完成';
        }
        if (!$order['payment_code']) {
            $order['payment_code'] = '无';
        }
        if ($order['payment_code'] == 1) {
            $order['payment_code'] = '微信';
        }
        if ($order['payment_code'] == 2) {
            $order['payment_code'] = '支付宝';
        }
        $order['createtime'] = date('Y-m-d H:i', $order['createtime']);
        if ($order['start_time']) {
            $order['start_time'] = date('Y-m-d H:i', $order['start_time']);
        } else {
            $order['start_time'] = '';
        }
        if ($order['return_time']) {
            $order['return_time'] = date('Y-m-d H:i', $order['return_time']);
        } else {
            $order['return_time'] = '';
        }
        if ($order['expire_time']) {
            $order['expire_time'] = date('Y-m-d H:i', $order['expire_time']);
        } else {
            $order['expire_time'] = '';
        }
        if (!$order['card_number']) {
            $order['card_number'] = '';
        }
        
        $data = array();
        $data['order'] = $order;
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 会员是否交押金
    */
    static public function if_cash($token)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        $member = Db::name('member')->where('id', $member_id)->find();
        $data = array();
        $data['if_deposit'] = $member['if_deposit'];
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 交押金
    */
    static public function create_cashorder($token, $order_id)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];
        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择要支付的订单');
        }
        //判断是否需要交押金
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id, 'order_status'=>4, 'if_cash'=>0))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'当前无此业务');
        }
        //生成订单
        $data = array();
        $order_sn = self::create_number(100, 999, 2, $member_id);
        $data['order_id'] = $order_id;
        $data['order_sn'] = $order_sn;
        $data['member_id'] = $member_id;
        $data['price'] = $order['cash_price'];
        $data['order_status'] = 1;
        $data['createtime'] = time();
        $count = Db::name('cashorder')->insertGetId($data);
        if (!$count) {
            return array('code'=>201, 'msg'=>'生成订单失败');
        }
        $arr = array();
        $arr['order_sn'] = $order_sn;
        $arr['price'] = $order['cash_price'];

        return array('code'=>200, 'msg'=>'成功', 'data'=>$arr);
    }

    /**
    * 押金支付
    */
    static public function pay_cash($token, $order_sn, $payment_code)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        if(!$order_sn){
            return array('code'=>201, 'msg'=>'订单号不能为空');
        }
        $order_info = Db::name('cashorder')->where(array('order_sn'=>$order_sn, 'order_status'=>1))->find();
        if(!$order_info){
            return array('code'=>201, 'msg'=>'订单异常');
        }
        if(!$payment_code){
            return array('code'=>201, 'msg'=>'请选择支付方式');
        }
        
        $out_trade_no = $order_sn;
        $total_fee = $order_info['price'];

        switch($payment_code)
        {
            case 1;
                $body = '尚博德睿'; //描述
                // $total_fee = $total_fee * 100;//支付金额(乘以100)
                $total_fee = 1;
                $notify_url = 'http://zuche.zhaojincong.top/home/api/cash_wxnotify/';//回调地址
                $wxpay = new WxPay();
                $result = $wxpay->unified_order($body,$total_fee,$out_trade_no,$notify_url);
                return array('code'=>200, 'msg'=>'成功', 'data'=>$result);
                break;
            case 2;
                $ali = new AliPay();
                $body = '尚博德睿'; //描述
                $total_fee = 0.01;
                $notify_url = 'http://zuche.zhaojincong.top/home/api/cash_alinotify/';//回调地址
                $result = $ali->aliPay($body,$total_fee,$out_trade_no,$notify_url);
                $data = array();
                $data['alipay'] = $result;
                return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
                break;
        }
    }

    /**
     * 微信回调
     */
    static public function cash_wxnotify() {  

        ini_set('date.timezone', 'Asia/Shanghai');
        error_reporting(E_ERROR);
        $xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $objectxml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = array();
        $json = json_encode($objectxml);
        $data = json_decode($json,true);
        $member_order = Db::name('cashorder')->where('order_sn', $data['out_trade_no'])->find();
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS' && $member_order['order_status'] == 1) {
            // 启动事务
            Db::startTrans();
            try{
                //修改订单状态
                $arr = array();
                $arr['order_status'] = 2;
                $arr['payment_code'] = 1;
                $arr['payment_time'] = time();
                Db::name('cashorder')->where('order_sn', $data['out_trade_no'])->update($arr);
                //修改租车订单
                $arr = array();
                $arr['if_cash'] = 1;
                Db::name('order')->where('id', $member_order['order_id'])->update($arr);

                Db::commit();
                return array('code'=>200, 'msg'=>'支付成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return array('code'=>201, 'msg'=>'支付失败');
            }
        }
    }

    /**
    * 支付宝回调
    */
    static public function cash_alinotify()
    {
        import('Alipay.AopClient',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr/u+YMMl4rKaDMuKa0QSg37Wk4ZcDoXz9I+v4MSYELwVLfu3CLmNWRrzH+6k2ivRaB0ZQl9e97Fud9MJTPJewYNC+LNTRhobW6DEm+H2Ffe4V1J9eSOs2giz0EAhKVggrqGsIUit1gmiuFPzi/9h6zsamOqFQ6zcNHwB19PORJDEIYAJ1ucleQwMUklfD4EttXXYQUqm94CTqbQJZwy9cr8J3buQ60N0S0cyPoHkw+jAJL8ZPkpDcYGOcDfiq/Op0bfIqYVQkJF1jFniDNNqfu68uq3BhxAeJRq0KuUgyNdTC8JAvV6rOsQ2cjlmspANfqQCf2bjCYnHEBUZFDbHGwIDAQAB';
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        $member_order = Db::name('cashorder')->where('order_sn', $_POST['out_trade_no'])->find();
        if($flag && !isset($_POST['refund_fee']) && $member_order['order_status'] == 1){
            // 启动事务
            Db::startTrans();
            try{
                //修改订单状态
                $arr = array();
                $arr['order_status'] = 2;
                $arr['payment_code'] = 2;
                $arr['payment_time'] = time();
                Db::name('cashorder')->where('order_sn', $_POST['out_trade_no'])->update($arr);

                //修改租车订单
                $arr = array();
                $arr['if_cash'] = 1;
                Db::name('order')->where('id', $member_order['order_id'])->update($arr);
                Db::commit();

                return array('code'=>200, 'msg'=>'支付成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return array('code'=>201, 'msg'=>'支付失败');
            }
        }
    }

    /**
    * 租赁到期时间
    */
    static public function member_expiration_time($token)
    {
        //判断登录
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];

        $where = array();
        $where['member_id'] = $member_id;
        $where['order_status'] = array('in', [2, 3, 4]);
        $order = Db::name('order')->where($where)->find();
        $data = array();
        if (!$order) {
            $data['if_order'] = 0;
            $data['time'] = '';
        } else {
            $data['if_order'] = 1;
            $data['time'] = date('Y-m-d', $order['expire_time']);
        }

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 站点列表
    */
    static public function station_list($address)
    {
        $data = array();
        if (!$address) {
            $area = Db::name('area')->where('if_default', 1)->find();
        } else {
            $area = Db::name('area')->where('name', $address)->find();
        }
        if (!$area) {
            $data['station'] = array();
        } else {
            $data['station'] = Db::name('station')->where('area_id', $area['id'])->field('id, name, address, lat, lng')->select();
        }
        
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
    * 提车点列表
    */
    static public function warehouse_list($address)
    {
        $data = array();
        if (!$address) {
            $area = Db::name('area')->where('if_default', 1)->find();
        } else {
            $area = Db::name('area')->where('name', $address)->find();
        }
        if (!$area) {
            $data['warehouse'] = array();
        } else {
            $data['warehouse'] = Db::name('warehouse')->where('area_id', $area['id'])->select();
        }
        
        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
     * 订单消息
     */
    static public function order_message($token, $num, $page)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];

        if (!$num) {
            $num = 6;
        }
        if (!$page) {
            $page = 1;
        }
        $start_num = ($page-1)*$num;
        $data = array();
        $count = Db::name('message_order')->where('member_id', $member_id)->count();
        $data['total_page'] = ceil($count/$num);
        $message_order = Db::name('message_order')->where('member_id', $member_id)->order('id desc')->limit($start_num, $num)->select();
        if ($message_order) {
            foreach ($message_order as $key => $value) {
                $message_order[$key]['createtime'] = date('Y-m-d H:i', $value['createtime']);
            }
        }
        $data['message_order'] = $message_order;

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
     * 系统消息
     */
    static public function system_list($num, $page)
    {
        if (!$num) {
            $num = 6;
        }
        if (!$page) {
            $page = 1;
        }
        $start_num = ($page-1)*$num;
        $data = array();
        $count = Db::name('message_system')->count();
        $data['total_page'] = ceil($count/$num);
        $message_system = Db::name('message_system')->order('id desc')->limit($start_num, $num)->select();
        if ($message_system) {
            foreach ($message_system as $key => $value) {
                $message_system[$key]['createtime'] = date('Y-m-d H:i', $value['createtime']);
            }
        }
        $data['message_system'] = $message_system;

        return array('code'=>200, 'msg'=>'成功', 'data'=>$data);
    }

    /**
     * 退车申请
     */
    static public function apply_back($token, $order_id)
    {
        if(!$token){
            return array('code'=>201, 'msg'=>'token不能为空');
        }
        //检测用户token 是否合法
        $check_member_token = self::check_member_token($token);
        if(isset($check_member_token['code']) && $check_member_token['code'] == 202){
            return $check_member_token;
        }
        $member_id = $check_member_token['member_id'];

        if (!$order_id) {
            return array('code'=>201, 'msg'=>'请选择订单');
        }
        $order = Db::name('order')->where(array('id'=>$order_id, 'member_id'=>$member_id, 'order_status'=>4))->find();
        if (!$order) {
            return array('code'=>201, 'msg'=>'订单异常');
        }
        $arr = array();
        $arr['order_status'] = 5;
        $result = Db::name('order')->where('id', $order_id)->update($arr);
        if (!$result) {
            return array('code'=>201, 'msg'=>'提交失败');
        }

        return array('code'=>200, 'msg'=>'申请成功，等待审核中');
    }

}